//
//  UIImage+LJThumbnail.m
//  Instruments-图片浏览
//
//  Created by 刘杰 on 2018/4/9.
//  Copyright © 2018年 Jeremy. All rights reserved.
//

#import "UIImage+LJThumbnail.h"

static NSString * directory = @"lj_thumbnail";

@implementation UIImage (LJThumbnail)

- (UIImage *)thumbnailWithSize:(CGSize)size isOpaque:(BOOL)opaque{
    UIImage *originalImage = self;
    if (size.width == 0) {
        size.width = size.height * (originalImage.size.width / originalImage.size.height);
    }
    
    if (size.height == 0) {
        size.height = size.width * (originalImage.size.height / originalImage.size.width);
    }
    
    // draw image in image context
    UIGraphicsBeginImageContextWithOptions(size, opaque, 1);
    [originalImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return thumbnailImage;
}
+ (UIImage *)thumbnailWithPath:(NSString *)path imageSize:(CGSize)size isOpaque:(BOOL)opaque compression:(CGFloat)Compression{
    UIImage *originalImage = [UIImage imageWithContentsOfFile:path];
    if (originalImage == nil) {
        return nil;
    }
    
    if (size.width == 0) {
        size.width = size.height * (originalImage.size.width / originalImage.size.height);
    }
    
    if (size.height == 0) {
        size.height = size.width * (originalImage.size.height / originalImage.size.width);
    }
    
    // draw image in image context
    UIGraphicsBeginImageContextWithOptions(size, opaque, 1);
    [originalImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // write to thumbnail image to TemporaryDirectory
    NSData *data = UIImageJPEGRepresentation(thumbnailImage, Compression);
    
    // check and create lj_thumbnail folder in TemporaryDirectory
    NSFileManager *manager = [NSFileManager defaultManager];
    
    NSString *thumbnailDirectory = [NSTemporaryDirectory() stringByAppendingPathComponent:directory];
    
    if (![manager fileExistsAtPath:thumbnailDirectory]) {
        [manager createDirectoryAtPath:thumbnailDirectory withIntermediateDirectories:NO attributes:nil error:NULL];
    }
    
    // get originalImage name
    
    NSString *imageName = [path stringByDeletingLastPathComponent];
    
    NSString *thumbnailPath = [thumbnailDirectory stringByAppendingPathComponent:imageName];
    
    [data writeToFile:thumbnailPath atomically:YES];
    
    return thumbnailImage;
}
@end
